package com.ljx.recruitment.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.security.common.UserContext;
import com.ljx.recruitment.security.util.UserUtil;
import com.ljx.recruitment.user.domain.dto.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-01  19:11
 */
@Component("tokenInterceptor")
public class TokenInterceptor implements HandlerInterceptor {

    // 白名单路径
    private String[] urls = new String[]{
            "/api/user/login", "/api/user/register", "/api/user/wxLogin", "/api/email/send",
            "/api/doc.html", "/api/swagger-resources", "/api/favicon.ico", "/api/webjars/**", "/api/error",
            "/api/tenant/info/**", "/api/tenant/code/**", "/api/tenant/search/filter", "/api/tenant/site/nav/list",
            "/api/job/page", "/api/job/info/**",
            "/api/druid.index", "/api/druid/**",
            "/api/oss/**",
            "/api/access_token/parse/**",
            "/api/product/trial/application",
            "/api/sms/send",
            "/api/job/home/show"
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String tenantId = request.getHeader("tenantId");
        if (StrUtil.isNotEmpty(tenantId)){
            UserContext.setTenantId(Long.parseLong(tenantId));
        }

        // AccessToken优先级比token高
        if (Objects.nonNull(UserContext.getUser())) {
            return true;
        }
        String requestURI = request.getRequestURI();
        String token = request.getHeader("token");
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String url : urls) {
            if (pathMatcher.match(url, requestURI)){
                if (StrUtil.isEmpty(token)){
                    return true;
                }
                break;
            }
        }

        if (StrUtil.isEmpty(token)){
            throw new ApiException("需要身份验证");
        }
        UserDto userDto = UserUtil.parseTokenToUser(token);
        if (Objects.isNull(userDto)){
            throw new ApiException("身份验证失败");
        }
        UserContext.setUser(userDto);

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
        UserContext.removeTenant();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
